<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="800px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <!-- 基本信息 -->
      <div class="basic-info mb-4">
        <div class="section-title">基本信息</div>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="检验类型编码" prop="typeCode">
              <el-input
                v-model="formData.typeCode"
                readonly
                placeholder="选择检验类型后自动生成"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="检验类型" prop="typeId" required>
              <el-select
                v-model="formData.typeId"
                :disabled="isView"
                placeholder="请选择检验类型"
                class="w-full"
                @change="handleTypeChange"
              >
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.DETECTION_TYPE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="Number(dict.value)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="关联工序" prop="processCode" required>
              <el-select
                v-model="formData.processCode"
                :disabled="isView"
                placeholder="请选择工序"
                class="w-full"
              >
                <el-option
                  v-for="item in processOptions"
                  :key="item.processName"
                  :label="item.processName"
                  :value="item.processCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="状态" prop="status" required>
              <el-checkbox
                v-model="formData.status"
                :disabled="isView"
                :true-value="1"
                :false-label="0"
                >启用
              </el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="关联产品" prop="itemCode">
              <el-select
                v-model="formData.itemCode"
                :disabled="isView"
                placeholder="请选择产品"
                filterable
                remote
                :remote-method="searchProducts"
                :loading="productLoading"
                class="w-full"
                clearable
              >
                <el-option
                  v-for="item in productOptions"
                  :key="item.itemCode"
                  :label="item.itemCode + item.itemName"
                  :value="item.itemCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="关联产线" prop="lineId">
              <el-select
                v-model="formData.lineId"
                :disabled="isView"
                placeholder="请选择产线"
                class="w-full"
              >
                <el-option
                  v-for="item in lineOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 检验项目明细 -->
      <div class="inspection-items">
        <div class="section-title">检验项目明细</div>
        <el-table :data="formData.items" border class="mb-2">
          <el-table-column label="类别">
            <template #default="{ row }">
              <el-select
                v-model="row.itemType"
                :disabled="isView"
                placeholder="请选择类别"
                class="w-full"
                @change="(val) => handleCategoryChange(val, row)"
              >
                <el-option
                  v-for="dict in categoryOptions"
                  :key="dict.itemType"
                  :label="dict.itemType"
                  :value="dict.itemType"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="检验项目编号">
            <template #default="{ row }">
              <el-select
                v-model="row.itemCode"
                :disabled="!row.itemType"
                placeholder="请选择检验项目"
                filterable
                remote
                @click="searchItems(row)"
                :loading="itemLoading"
                @change="(value) => handleItemChange(value, row)"
                class="w-full"
              >
                <el-option
                  v-for="item in itemOptions"
                  :key="item.itemCode"
                  :label="item.itemCode"
                  :value="item.itemCode"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="检验项目名称" prop="itemName" align="center" />
          <el-table-column label="参数类型" align="center" prop="paramType">
            <template #default="{ row }">
              {{ getDictLabel(row.paramType) }}
            </template>
          </el-table-column>
          <el-table-column label="检测值个数">
            <template #default="{ row }">
              <el-input
                v-model="row.nums"
                type="number"
                :min="1"
                placeholder="请输入正整数，默认为1"
                @change="validateNumber(row)"
                remote
                class="w-full"
              />
            </template>
          </el-table-column>
          <el-table-column v-if="!isView" label="操作" align="center">
            <template #default="{ $index }">
              <el-button link type="danger" @click="removeItem($index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div v-if="!isView" class="text-left">
          <el-button
            type="primary"
            @click="addItem"
            :disabled="!formData.lineId && !formData.processCode"
            >添 加
          </el-button>
        </div>
      </div>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button v-if="!isView" type="primary" @click="submitForm" :loading="formLoading"
        >确 定
      </el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { InspectionTypeApi, InspectionTypeVO } from '@/api/opticore/inspection/type'
import * as DictDataApi from '@/api/system/dict/dict.data'
import { ProcessInfoApi } from '@/api/opticore/processinfo'
import { BomListPlcApi } from '@/api/opticore/bomlistplc'
import { InspectionItemApi } from '@/api/opticore/inspection/item'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import { Message } from '@/layout/components/Message'

/** 检验类型 表单 */
defineOptions({ name: 'InspectionTypeForm' })

console.log(111, getStrDictOptions(DICT_TYPE.DETECTION_TYPE))

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中
const formType = ref('') // 表单的类型：create - 新增；update - 修改

// 表单数据
const formData = ref({
  id: undefined,
  typeCode: undefined,
  typeId: undefined,
  processCode: undefined,
  itemCode: undefined,
  lineId: undefined,
  status: 1, // 默认启用
  items: [] // 检验项目明细
})

// 表单校验规则
const formRules = reactive({
  // typeCode: [{ required: true, message: '请输入检验编码', trigger: 'blur' }],
  typeId: [{ required: true, message: '请选择检验类型', trigger: 'change' }],
  processCode: [{ required: true, message: '请选择工序', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
})

const formRef = ref() // 表单 Ref

// 各种选项数据
const paramsOptions = ref([]) // 存储字典数据
const typeOptions = ref([]) // 检验类型选项
const processOptions = ref([]) // 工序选项
const productOptions = ref([]) // 产品选项
const lineOptions = ref([]) // 产线选项
const categoryOptions = ref([]) // 类别选项
const itemOptions = ref([]) // 检验项目选项

// 加载状态
const productLoading = ref(false)
const itemLoading = ref(false)

// 是否为查看模式
const isView = ref(false)

const core = ref(1)

watch(
  () => formData.value.itemCode,
  async (newItemCode, oldItemCode) => {
    if (!typeId.value) {
      if (newItemCode && newItemCode !== oldItemCode) {
        core.value = await BomListPlcApi.getCoreByItemCode(newItemCode)
        formData.value.items.forEach((row) => (row.nums = core.value))
        return
      }
      // 处理清楚品号的逻辑
      if (newItemCode === undefined || oldItemCode) {
        formData.value.items.forEach((row) => (row.nums = 1))
        core.value = 1
      }
    }
  },
  { immediate: false } // 是否立即执行（默认false)
)

const validateNumber = (row) => {
  // 转换为数字并处理可能的字符串输入
  const num = Number(row.nums)

  // 检查是否为有效数字且≥1
  if (isNaN(num)) {
    message.warning('请输入有效的数字！')
    row.nums = core.value
    return
  }

  // 取整处理
  const intValue = Math.floor(num)
  if (intValue >= 1) {
    // 只有当值有变化时才更新（避免不必要的触发）
    if (row.nums !== intValue) {
      row.nums = intValue
    }
  } else {
    message.warning('请输入大于等于1的整数！')
    row.nums = core.value
  }
}

const typeId = ref()

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  console.log(1,type)
  typeId.value = id
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  // dialogTitle.value = id?'编辑':'查看'
  formType.value = type
  isView.value = type === 'query' // 设置查看模式
  resetForm()
  // 加载选项数据
  await Promise.all([
    //loadTypeOptions(),
    loadProcessOptions(),
    //loadLineOptions(),
    loadCategoryOptions()
  ])

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await InspectionTypeApi.getInspectionType(id)
      console.log('info', formData.value.processCode)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open })

/** 加载各种选项数据的方法 */
const loadTypeOptions = async () => {
  // TODO: 从后端获取检验类型选项
  const data = await DictDataApi.getDictDataPage({ dictType: 'detection_type' })
  typeOptions.value = data.list
}

// 初始化加载字典
onMounted(async () => {
  paramsOptions.value = await getStrDictOptions(DICT_TYPE.ARGS_VALUE_TYPE)
  lineOptions.value = await getStrDictOptions(DICT_TYPE.OPTICORE_LINE)
  typeOptions.value = await getStrDictOptions(DICT_TYPE.DETECTION_TYPE)
})

const getDictLabel = (value) => {
  const option = paramsOptions.value.find((item) => item.value === value)
  return option ? option.label : value
}

const loadProcessOptions = async () => {
  // TODO: 从后端获取工序选项
  const queryParams = reactive({
    pageNo: 1,
    pageSize: 100
  })
  const data = await ProcessInfoApi.getProcessInfoPage(queryParams)
  processOptions.value = data.list
}

const loadLineOptions = async () => {
  // TODO: 从后端获取产线选项
  // TODO: 从后端获取检验类型选项
  const data = await DictDataApi.getDictDataPage({ dictType: 'opticore_line' })
  lineOptions.value = data.list
}

const loadCategoryOptions = async () => {
  // TODO: 从后端获取类别选项
  categoryOptions.value = await InspectionItemApi.getInspectionTypeList()
  console.log(categoryOptions.value)
}

/** 搜索产品 */
const searchProducts = async (query: string) => {
  if (query) {
    productLoading.value = true
    try {
      const params = {
        pageNo: 1,
        pageSize: 9999,
        itemCode: query
      }
      const data = await BomListPlcApi.getBomListPlcPage(params)
      // TODO: 调用后端接口搜索产品
      productOptions.value = data.list
    } finally {
      productLoading.value = false
    }
  }
}

/** 搜索检验项目 */
const searchItems = async (row: any) => {
  console.log(row)

  if (!row.itemId) {
    return
  }

  if (!row.itemType) {
    return
  }

  console.log('........')
  itemLoading.value = true
  try {
    // TODO: 调用后端接口搜索检验项目
    // itemOptions.value = await api.searchItems(query)
    itemOptions.value = await InspectionItemApi.getInspectionItemListByType({
      itemType: row.itemType
    })
  } finally {
    itemLoading.value = false
  }
}

/** 检验项目选择变化时 */
const handleItemChange = (value: string, row: any) => {
  const duplicate = formData.value.items.some(
    (item) =>
      item !== row && // 排除自己
      item.itemType === row.itemType &&
      item.itemCode === value
  )

  if (duplicate) {
    message.warning('相同类别下不能重复添加相同的检验项目')
    // 清空非法选择
    row.itemCode = undefined
    row.itemName = undefined
    row.itemId = undefined
    return
  }
  // TODO: 根据选择的检验项目编号设置名称
  // 从选项中找到对应的检验项目
  const selectedItem = itemOptions.value.find((item) => item.itemCode === value)
  if (selectedItem) {
    // 设置检验项目名称
    row.itemName = selectedItem.itemName
    row.paramType = selectedItem.paramType
    row.itemId = selectedItem.id
  }
}

/** 当类别变化时，清空对应的检验项目编号等，并重新加载项目选项 */
const handleCategoryChange = async (value: string, row: any) => {
  row.itemCode = undefined
  row.itemName = undefined
  row.itemId = undefined

  // 可选：自动触发搜索加载新的项目选项
  itemLoading.value = true
  try {
    itemOptions.value = await InspectionItemApi.getInspectionItemListByType({
      itemType: value
    })
  } finally {
    itemLoading.value = false
  }
}

/** 处理检验类型变更 */
const handleTypeChange = async () => {
  formLoading.value = true
  try {
    // TODO: 调用后端接口获取检验类型编码
    if (!formData.value.typeCode) {
      formData.value.typeCode = await InspectionTypeApi.getTypeCode()
    }
    // ✅ 清空检验项目明细中的项目编号和名称
    formData.value.items = ref([])
  } catch (error) {
    message.error('获取检验类型编码失败')
  } finally {
    formLoading.value = false
  }
}

/** 添加检验项目 */
const addItem = () => {
  formData.value.items.push({
    itemId: undefined,
    nums: core.value
  })
}

/** 删除检验项目 */
const removeItem = (index: number) => {
  formData.value.items.splice(index, 1)
}

/** 提交表单 */
const emit = defineEmits(['success'])
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()

  // ✅ 校验每一行的“类别”和“检验项目编号”
  for (const [index, item] of formData.value.items.entries()) {
    if (!item.itemType) {
      message.warning(`第 ${index + 1} 行的“类别”不能为空`)
      return
    }
    if (!item.itemCode) {
      message.warning(`第 ${index + 1} 行的“检验项目编号”不能为空`)
      return
    }
  }

  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as InspectionTypeVO
    if (formType.value === 'create') {
      await InspectionTypeApi.createInspectionType(data)
      message.success(t('common.createSuccess'))
    } else {
      await InspectionTypeApi.updateInspectionType(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    typeCode: undefined,
    typeId: undefined,
    processCode: undefined,
    itemCode: undefined,
    lineId: undefined,
    status: 1,
    items: []
  }
  formRef.value?.resetFields()
}
</script>

<style lang="scss" scoped>
.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 16px;
  text-align: left;
  position: relative;
  padding-left: 12px;

  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 4px;
    height: 16px;
    background-color: #409eff;
    border-radius: 2px;
  }
}

.basic-info,
.inspection-items {
  padding: 16px;
  background-color: #fff;
  border-radius: 4px;
}
</style>

<style lang="scss" scoped>
.title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 1px;
}

.basic-info {
  background-color: #fff;
  padding: 16px;
  border-radius: 4px;
}

.inspection-items {
  background-color: #fff;
  padding: 16px;
  border-radius: 4px;
}

:deep(.el-form-item__label) {
  font-weight: normal;
}

:deep(.el-table) {
  margin-top: 8px;
}

.w-full {
  width: 100%;
}
</style>
